/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package simulator;

import javax.vecmath.Color3f;
import javax.vecmath.Vector3f;
import org.jdom.Attribute;
import org.jdom.DataConversionException;
import org.jdom.Element;

/**
 *
 * @author vdelaitr
 */
public class XMLParser {
    // One exeption for the class GeometryParser
    public static class XMLParserException extends Exception {
        XMLParserException(String message) {
            super(message);
        }
    }

    static float parseValue(Element e) throws XMLParserException {
        try {
            return Float.parseFloat(e.getValue());
        }
        catch(NumberFormatException ex) {
            throw new XMLParserException("Bad numeric float value : \"" + e.getValue() +"\"\n" + ex.getMessage());
        }
    }

    static float parseFloatAttr(Element root, String attr) throws XMLParserException {
        Attribute a = root.getAttribute(attr);
        try {
            if (a != null) {
                return a.getFloatValue();
            }
            else {
                throw new XMLParserException("Missing \"" + attr + "\" attribute.");
            }
        }
        catch(DataConversionException e) {
            throw new XMLParserException("Bad numeric float value : \"" + a.getValue() +"\"\n" + e.getMessage());
        }
    }

    static float parseFloatChild(Element root, String child) throws XMLParserException  {
        Element e = root.getChild(child);
        if (e != null) {
            return parseValue(e);
        }
        else {
            throw new XMLParserException("Missing \"" + child + "\" element.");
        }
    }

    static Vector3f parseVector(Element root) throws XMLParserException {
        float x, y, z;
        
        if (root.getChildren().isEmpty()) {
            x = parseFloatAttr(root, "x");
            y = parseFloatAttr(root, "y");
            z = parseFloatAttr(root, "z");
        }
        else {
            x = parseFloatChild(root, "x");
            y = parseFloatChild(root, "y");
            z = parseFloatChild(root, "z");
        }

        return new Vector3f(x, y, z);
    }

    static Color3f parseColor(Element root) throws XMLParserException {
        float r, g, b;

        if (root.getChildren().isEmpty()) {
            r = parseFloatAttr(root, "r");
            g = parseFloatAttr(root, "g");
            b = parseFloatAttr(root, "b");
        }
        else {
            r = parseFloatChild(root, "r");
            g = parseFloatChild(root, "g");
            b = parseFloatChild(root, "b");
        }

        return new Color3f(r, g, b);
    }
}
